package eai.tp2.lpco.ws.shippingdepartment;

import java.util.Properties;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import eai.tp2.lpco.database.Order;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.database.Order.Status;
import eai.tp2.lpco.purchase.IPurchase;
import eai.tp2.lpco.requests.IRequest;

@WebService(targetNamespace = "http://eai/tp2/ShipDpt", serviceName = "StartShippingService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@Remote(IStartShipping.class)
@Stateless
public class StartShipping implements IStartShipping {

	@WebMethod
	public boolean orderProcessed(int numOrder) {		
		try {
			System.out.println("A ENVIAR MAIL");
			InitialContext ctx = null;
			IPurchase purchase = null;
			IRequest request = null;
			ctx = new InitialContext();
			purchase = (IPurchase) ctx.lookup("PurchaseBean/remote");
			request = (IRequest) ctx.lookup("RequestBean/remote");
			purchase.changeStatus(numOrder, Status.DELIVERED);
			Order order = request.getOrder(numOrder);
			User user = order.getUser();
			postMail(user.getEmail(), "LPCO Order Processed", "The order was processed. This message was generated automatically. Please, don't reply.", "LPCO");
			return true;
		} catch (MessagingException e) {			
			e.printStackTrace();			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		return false;
	}

	private void postMail(String to, String subject, String message,
			String from) throws MessagingException {
		
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "smtp.dei.uc.pt");
		properties.put("mail.smtp.port", "25");
		
		Session session = Session.getDefaultInstance(properties, null);
		
		Message msg = new MimeMessage(session);				
		msg.setFrom(new InternetAddress(from));
		msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));	
		msg.setSubject(subject);
		msg.setText(message);
	
		Transport.send(msg);
	}

}